package simplify.ur.life.rasberryswitch;

import simplify.ur.life.rasberryswitch.util.ChangeLogDialog;
import simplify.ur.life.rasberryswitch.util.SystemUiHider;
import simplify.ur.life.rasberryswitch.util.Ut;
import simplify.ur.life.rasberryswitch.util.ssh.SshConnection;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Switch;
import android.widget.Toast;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 * 
 * @see SystemUiHider
 */
public class SwitcherActivity extends Activity {
	Button connectButton;
	public static int MAX_SCHALTER = 8;
	Switch schalter[] = new Switch[MAX_SCHALTER];
	int switchids[] = new int[MAX_SCHALTER];
	public static final int ACTIVITY_ID_PREF = 1234;

	SshConnection sshConnection;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_switcher);

		final View controlsView = findViewById(R.id.fullscreen_content_controls);
		connectButton = (Button) findViewById(R.id.dummy_button);
		if (connectButton != null) {
			connectButton.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					if ((sshConnection != null)
							&& (sshConnection.isConnected())) {
						closeSSHConnection();
					} else {
						openSSHConnection();
					}
				}
			});
		}

		schalter[0] = (Switch) controlsView.findViewById(R.id.switch1);
		schalter[1] = (Switch) controlsView.findViewById(R.id.switch2);
		schalter[2] = (Switch) controlsView.findViewById(R.id.switch3);
		schalter[3] = (Switch) controlsView.findViewById(R.id.switch4);
		schalter[4] = (Switch) controlsView.findViewById(R.id.switch5);
		schalter[5] = (Switch) controlsView.findViewById(R.id.switch6);
		schalter[6] = (Switch) controlsView.findViewById(R.id.switch7);
		schalter[7] = (Switch) controlsView.findViewById(R.id.switch8);

		switchids[0] = R.id.switch1;
		switchids[1] = R.id.switch2;
		switchids[2] = R.id.switch3;
		switchids[3] = R.id.switch4;
		switchids[4] = R.id.switch5;
		switchids[5] = R.id.switch6;
		switchids[6] = R.id.switch7;
		switchids[7] = R.id.switch8;

		SharedPreferences sharedPreferences = PreferenceManager
				.getDefaultSharedPreferences(SwitcherActivity.this);

		for (int i = 0; i < MAX_SCHALTER; i++) {

			schalter[i].setText(sharedPreferences.getString("SwitchLabelText"
					+ (i + 1), "Schalter"));

			schalter[i].setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					callScript(v.getId(), ((Switch) v).isChecked());

				}
			});

			//
			// OnCheckedChangeListener(new
			// CompoundButton.OnCheckedChangeListener() {
			// @Override
			// public void onCheckedChanged(CompoundButton buttonView,
			// boolean isChecked) {
			//
			// callScript(buttonView.getId(), isChecked);
			//
			// if (isChecked) {
			// // The toggle is enabled
			// } else {
			// // The toggle is disabled
			// }
			// }
			// });
		}
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);

		ChangeLogDialog cl = new ChangeLogDialog(this);
		if (cl.firstRun())
			cl.getLogDialog().show();

	}

	@Override
	protected void onResume() {
		super.onResume();
		openSSHConnection();
	}

	@Override
	protected void onDestroy() {
		closeSSHConnection();
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(final Menu menu) {
		super.onCreateOptionsMenu(menu);

		final MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(final MenuItem item) {
		// super.onOptionsItemSelected(item);
		boolean result = false;
		switch (item.getItemId()) {

		case (R.id.settings): {
			startActivityForResult(new Intent(this, SettingActivity.class),
					ACTIVITY_ID_PREF);

			result = true;
			break;
		}
		case (R.id.about): {

			ChangeLogDialog cl = new ChangeLogDialog(this);
			cl.getFullLogDialog().show();
			result = true;
			
			// // showDialogPrivate(R.id.about);
			//
			// final AboutDialogFragment newFragment =
			// AboutDialogFragment.newInstance();
			// newFragment.show(getSupportFragmentManager(), "dialog");
			//
			// result = true;
			// break;
		}
		}
		return result;
	}

	@Override
	protected void onActivityResult(final int requestCode,
			final int resultCode, final Intent data) {
		switch (requestCode) {
		case ACTIVITY_ID_PREF: // R.id.settings_activity_closed:
			finish();
			startActivity(new Intent(this, this.getClass()));
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	void callScript(int id, boolean onOff) {
		SharedPreferences sharedPreferences = PreferenceManager
				.getDefaultSharedPreferences(SwitcherActivity.this);

		Switch button = null;
		String cmd = sharedPreferences.getString("SSHCMD", "ls");
		// getResources().getIntArray(R.array.switchids);
		int i = 0;
		for (; i < switchids.length; i++) {
			// Ut.i("s " + switchids[i] + ", " + id);
			if (switchids[i] == id) {
				button = schalter[i];
				Ut.i("Button " + i + " switched");
				break;
			}
		}
		String param = sharedPreferences.getString((onOff ? "CmdON" : "CmdOFF")
				+ (i + 1), "TEST" + (i + 1));

		cmd += " " + param;

		RunSSHCommandTask task = new RunSSHCommandTask(cmd, button);
		task.execute((Void) null);

	}

	void openSSHConnection() {
		closeSSHConnection();

		GetSSHConnectionTask task = new GetSSHConnectionTask();
		task.execute((Void) null);

	}

	private void closeSSHConnection() {
		if (sshConnection != null) {
			if (sshConnection.isConnected()) {
				sshConnection.disconnect();
			}
			sshConnection = null;
		}
		toggleButtons(false);
	}

	public void toggleButtons(boolean enable) {
		if (connectButton != null) {
			connectButton.setText((enable) ? R.string.disconnect
					: R.string.connect);
			connectButton.setEnabled(true);
		}
		for (int i = 0; i < MAX_SCHALTER; i++) {
			schalter[i].setEnabled(enable);
		}

	}

	public class GetSSHConnectionTask extends
			AsyncTask<Void, Void, SshConnection> {

		SharedPreferences sharedPreferences = PreferenceManager
				.getDefaultSharedPreferences(SwitcherActivity.this);

		@Override
		protected SshConnection doInBackground(final Void... params) {

			SwitcherActivity.this.sshConnection = new SshConnection();
			Ut.i("try to connect");
			SwitcherActivity.this.sshConnection
					.connect(sharedPreferences.getString("SSHServerName",
							"www.smek.at"), sharedPreferences.getString(
							"SSHUser", "pi"), sharedPreferences.getString(
							"SSHPWD", "changeit01"));
			Ut.i("after connect");

			return SwitcherActivity.this.sshConnection;

		}

		@Override
		protected void onPostExecute(final SshConnection connection) {
			Toast.makeText(
					SwitcherActivity.this,
					(connection != null) && (connection.isConnected()) ? "Connected"
							: "NOT connected to "
									+ sharedPreferences.getString(
											"SSHServerName", "www.target.org"),
					Toast.LENGTH_LONG).show();

			toggleButtons((connection != null) && (connection.isConnected()));

			if ((SwitcherActivity.this.sshConnection != null)
					&& (SwitcherActivity.this.sshConnection.isConnected())) {
				// check initial state

				// DUMMY FOR NOW !!!!
				// ONLY DONE FOR SCHALTER 1 == GPIO PIN 17
				String cmd = sharedPreferences.getString("SSHCMD", "ls");
				RunSSHCommandTask task = new RunSSHCommandTask(cmd,
						SwitcherActivity.this.schalter[0]);
				task.execute((Void) null);
			}

		}
	}

	public class RunSSHCommandTask extends AsyncTask<Void, Void, String> {

		String command;
		Switch button;

		RunSSHCommandTask(String cmd, Switch v) {
			super();
			command = cmd;
			button = v;
		}

		@Override
		protected void onPreExecute() {

			if (button != null) {
				button.setEnabled(false);
			}
		}

		@Override
		protected String doInBackground(final Void... params) {

			String result = sshConnection.executeCommand(command);

			if (result != null) {
				result = result.trim();
			}
			return result;
		}

		@Override
		protected void onPostExecute(final String result) {
			if (button != null) {
				button.setEnabled(true);
			}

			// TODO: OK value is hardcoded !!! <-- GPIO.c !?!
			button.setChecked((result != null) && ((result.contains("high"))));

			Toast.makeText(SwitcherActivity.this,
					(result != null) ? "Result is: " + result : "NO result",
					Toast.LENGTH_SHORT).show();

		}
	}

}
